//渲染分类
(async () => {
  const res = await axios({
    url: ' http://127.0.0.1:3000/api/category'
  })
  const xuanze = document.querySelector('[name="xuanze"]')
  if (!res.data.code) {
    let str = '<option value="999" disabled selected>请选择诗篇分类</option>'
    str += res.data.msg.map(item => `<option value="${item.theme_id}">${item.theme_name}</option>`
    ).join('')
    xuanze.innerHTML = str
  }
})();
//点击按钮后四秒后显示结果并且禁用按钮
const btn = document.querySelector('.card1 button');
function generatePoetry() {
  btn.innerHTML = '正在生成中,请稍等...'
  btn.disabled = true;
  result.style.opacity = '0';
}

//渲染结果
const ta = document.querySelector("#prompt1")
const div1 = document.querySelector(".cardy1")
const div2 = document.querySelector(".cardy2")
const div3 = document.querySelector(".cardy3")
const result = document.getElementById('result');
btn.addEventListener("click", async function () {
  if (ta.value.trim() == '') {
    alert('请输入内容')
    return
  }
  generatePoetry()
  const res = await axios({
    url: "http://localhost:3000/api/aicrete",//请求地址
    params: {
      prompt: ta.value,//prompt为用户输入的文本
    }
  })
  div1.innerHTML = `
          <h3 class="text-lg text-primary font-medium mb-4">${res.data.msg.creativeDirections[0].themeVariant}</h3>
          <div class="space-y-3">
            <p><span class="font-medium">意象：</span>${res.data.msg.creativeDirections[0].imagery}</p>
            <p><span class="font-medium">修辞：</span>${res.data.msg.creativeDirections[0].rhetoric}</p>
            <p><span class="font-medium">情感：</span>${res.data.msg.creativeDirections[0].emotion}</p>
          </div>
        `
  div2.innerHTML = `
        <h3 class="text-lg text-primary font-medium mb-4">${res.data.msg.creativeDirections[1].themeVariant}</h3>
        <div class="space-y-3">
          <p><span class="font-medium">意象：</span>${res.data.msg.creativeDirections[1].imagery}</p>
          <p><span class="font-medium">修辞：</span>${res.data.msg.creativeDirections[1].rhetoric}</p>
          <p><span class="font-medium">情感：</span>${res.data.msg.creativeDirections[1].emotion}</p>
        </div>
      `
  div3.innerHTML = `
          <div class="mb-8">
            <h3 class="text-lg text-primary font-medium mb-4">引导问题</h3>
            <div class="space-y-4">
              <div class="flex items-start gap-4">
                <div class="w-6 h-6 bg-primary text-white rounded-full flex items-center justify-center flex-shrink-0">1
                </div>
                <p class="text-gray-700">${res.data.msg.guidingQuestions[0]}</p>
              </div>
              <div class="flex items-start gap-4">
                <div class="w-6 h-6 bg-primary text-white rounded-full flex items-center justify-center flex-shrink-0">2
                </div>
                <p class="text-gray-700">${res.data.msg.guidingQuestions[1]}</p>
              </div>
            </div>
          </div>
          <div>
            <h3 class="text-lg text-primary font-medium mb-4">风格建议</h3>
            <div class="flex gap-4">
              <span class="px-4 py-2 bg-secondary text-primary rounded-full text-sm">${res.data.msg.styleSuggestions[0]}</span>
              <span class="px-4 py-2 bg-secondary text-primary rounded-full text-sm">${res.data.msg.styleSuggestions[1]}</span>
            </div>
          </div>
          `
  result.style.opacity = '1';
  this.disabled = false;
  this.innerHTML = '生成诗歌灵感'
})


// 提交用户作品
!(async () => {
  const tj = document.querySelector('#khtj')
  tj.addEventListener('click', async () => {
    const data = {
      user_id: localStorage.getItem('user_id'),
      title: document.querySelector('#prompt').value,
      theme_id: document.querySelector('[name="xuanze"]').value,
      content: document.querySelector('#prompt2').value,
      author: localStorage.getItem('username')
    }
    if (!data.title || !data.content || data.theme_id == '999') {
      myAlert(false, '请填写完整信息')
      return
    }
    const res = await axios({
      url: "http://localhost:3000/api/postPoem",
      method: 'post',
      data
    })
    if (res.data.code == 200) {
      document.querySelector('#prompt').value = ''
      document.querySelector('#prompt2').value = ''
      document.querySelector('[name="xuanze"]').value = '999'
      myAlert(true, '提交成功')
      renderr()
    }
  })
})()

//点击跳转创作
!(() => {
  const div = document.querySelector('.w-full')
  div.addEventListener('click', () => {
    const cz = document.querySelector('.flex-col .text-xl')
    window.scrollTo(0, cz.offsetTop)
  })
})()


//tab栏切换
document.querySelectorAll('.tab-btn').forEach(button => {
  button.addEventListener('click', () => {
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.classList.remove('tab-active');
      btn.classList.add('text-gray-500');
    });
    button.classList.remove('text-gray-500');
    button.classList.add('tab-active');

    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.remove('active');
    });
    document.getElementById(button.dataset.tab).classList.add('active');
  });
});

//时间处理函数
function convertTimestampToLocalTime(timestamp) {
  const date = new Date(timestamp);
  const localYear = date.getFullYear();
  const localMonth = String(date.getMonth() + 1).padStart(2, '0');
  const localDay = String(date.getDate()).padStart(2, '0');
  const localHour = String(date.getHours()).padStart(2, '0');
  const localMinute = String(date.getMinutes()).padStart(2, '0');
  return `${localYear}-${localMonth}-${localDay} ${localHour}:${localMinute}`;
}


// 清理文本
function addBrToText(text) {
  const pattern = /([，。！？\s])/g;
  return text.replace(pattern, '$1<br>');
}

//渲染分类
const content = document.querySelectorAll('.tab-content')
console.log(content[1].children[1]);
async function renderr() {
  const res = await axios({
    url: "http://localhost:3000/api/getpoemsall",
  })
  if (!res.code) {
    const obj = res.data.msg
    console.log(obj);
    for (let key in obj) {
      content[key % 8].children[1].innerHTML += obj[key].map(item => `
             <div  data-id="${item.poem_id}" class="poetry-card bg-white p-6 rounded-lg border border-gray-100">
                   <h3 class="text-xl font-bold mb-2">${item.title}</h3>
                   <div class="flex items-center space-x-2 text-sm text-gray-500 mb-3">
                     <span>${item.nickname}</span>
                     <span>·</span>
                     <span>${convertTimestampToLocalTime(item.created_at)}</span>
                   </div>
                   <p class="text-gray-600 line-clamp-4">
                     ${addBrToText(item.content)}
                   </p>
                   <div class="mt-4 flex items-center justify-between text-sm text-gray-500">
                     <span>点赞 ${item.likes_count}</span>
                     <span>评论 ${item.comment_count}</span>
                   </div>
                 </div>
                `).join("")
    }
  }
}
renderr()

//跳转评论区
// 封装点击跳转函数
function setupRedirect(elementId) {
  const element = document.getElementById(elementId);
  if (element) {
      element.addEventListener('click', function (event) {
          let target = event.target;
          // 向上查找具有 data-id 属性的元素
          while (target && !target.dataset.id) {
              target = target.parentElement;
          }
          if (target && target.dataset.id) {
              const poemId = target.dataset.id;
              window.location.href = `../detail/index.html?poem_id=${poemId}`;
          }
      });
  }
}

// 定义需要设置跳转的元素 ID 数组
const elementIds = ['sx', 'ss','aq','yq','lz','lb','ag'];

// 使用 map 方法遍历数组并调用 setupRedirect 函数
elementIds.map(setupRedirect);
  